/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.google.code.twiddling.core.clp.setter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.google.code.twiddling.core.clp.CLParsingException;

/**
 * @author <a href="mailto:jeff.yuchang@gmail.com">Jeff Yu</a>
 *
 */
public class MethodSetter implements Setter {

	private Object bean;
	
	private Method method;
	
	public MethodSetter(Object object, Method method) {
		this.bean = object;
		this.method = method;
		if (method.getParameterTypes().length != 1) {
			throw new RuntimeException("Illegal method signature!");
		}
	}

	public String getName() {
		return method.getName();
	}

	public Class getType() {
		return method.getParameterTypes()[0];
	}

	public boolean isMultiValued() {
		return false;
	}

	public void set(Object value) throws CLParsingException {
        try {
            try {
                method.invoke(bean, value);
            }
            catch (IllegalAccessException ignore) {
                method.setAccessible(true);

                try {
                    method.invoke(bean, value);
                }
                catch (IllegalAccessException e) {
                    throw new IllegalAccessError(e.getMessage());
                }
            }
        }
        catch (InvocationTargetException e) {
            // Decode or wrap the target exception
            Throwable t = e.getTargetException();

            if (t instanceof RuntimeException) {
                throw (RuntimeException)t;
            }
            if (t instanceof Error) {
                throw (Error)t;
            }
            if (t instanceof CLParsingException) {
                throw (CLParsingException)t;
            }

            if (t != null) {
                throw new CLParsingException(t);
            }
            else {
                throw new CLParsingException(e);
            }
        }
    }
	
}
